package com.spring.framework.utils;


import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;

/**
 * @Author: Xiaohei
 * @CreateTime: 2021/12/2 21:57
 */
public class ReflectionUtil {

    public static Set<Class<?>> getClasses(String packagePath) throws IOException {
        LinkedHashSet<Class<?>> classes = new LinkedHashSet<>();
        String path = packagePath.replace('.', '/');
        Enumeration<URL> dirs = Thread.currentThread().getContextClassLoader().getResources(path);
        while (dirs.hasMoreElements()) {
            URL url = dirs.nextElement();
            String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
            File file = new File(filePath);
            File[] files = file.listFiles();
            List<File> fileList = new ArrayList<>();
            for (File file1 : files) {
                fileList.add(file1);
            }
            for (int i = 0; i < fileList.size(); i++) {
                File file1 = fileList.get(i);
                if (file1.isDirectory()) {
                    File[] files1 = file1.listFiles();
                    if (files1==null) {
                        continue;
                    }
                    for (File file2 : files1) {
                        fileList.add(file2);
                    }
                }else {
                    if (file1.getName().endsWith(".class")) {
                        String className = file1.getName().substring(0, file1.getName().length() - 6);
                        try {
                            String absolutePath = file1.getAbsolutePath();
                            int i1 = absolutePath.indexOf(path.replace("/", "\\"));
                            String substring = absolutePath.substring(i1);
                            substring = substring.replace('\\', '.').substring(0, substring.length() - 6);
                            if (substring.endsWith("$1")) {
                                continue;
                            }
                            Class<?> clazz = Class.forName(substring);
                            classes.add(clazz);
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return classes;
    }
}
